package configurationBusiness;

import easyDAO.SqlDispatch;
import impl.TestServerBusinessImpl;
import models.MyConfig;
import models.ReturnJson;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by yangxianming on 2020/09/17.
 * 1.从福员外页面获取session信息，以便登陆福员外
 */
public class DataCatch implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        ReturnJson returnJson = new ReturnJson();
        SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
        String action = request.getParameter("action");

        //UPDATE variable SET `value` = "abc" WHERE `key`="fuyuanwai_session"
        if (Objects.equals("getData", action)){
            String string = request.getParameter("string");
            System.out.println(string);
            if (isNullBack(string)){
                returnJson.setApiStatus(0);
                returnJson.setResult("string null or \"\"");
                return returnJson.toString();
            }
            if (!string.contains("JSESSIONID")){
                returnJson.setApiStatus(0);
                returnJson.setResult("can not found JSESSIONID!!");
                return returnJson.toString();
            }
            String jsessionid = getJSESSIONID(string);
            if (isNullBack(jsessionid)){
                returnJson.setApiStatus(0);
                returnJson.setResult("jsessionid null or \"\"");
                return returnJson.toString();
            }
            String sql = "UPDATE variable SET `value` = \"" + jsessionid + "\" WHERE `key`=\"fuyuanwai_session\"";
            sqlDispatch.update(sql);
        }
        returnJson.setResult("update success!!");
        return returnJson.toString();
    }

    private boolean isNullBack(String string){
        return Objects.equals(string, null) || Objects.equals(string, "");
    }

    private String getJSESSIONID(String string){
        int l = string.indexOf("JSESSIONID=") + 11;
        return string.substring(l, l+32);
    }
}
